<template>
  <div class="min-h-screen bg-gray-50 ">
    <!-- 搜索和操作栏 -->
    <div class="mb-1 flex justify-between items-center">
      <div>
        <a-button class="flex items-center" @click="router.push('/system/basicSettings')">
          <template #icon>
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M11 15l-3-3m0 0l3-3m-3 3h8M3 12a9 9 0 1118 0 9 9 0 01-18 0z" />
            </svg>
          </template>
          返回
        </a-button>
      </div>
      <div class="flex items-center space-x-2 flex-wrap gap-y-1">
        <a-input v-model:value="filters.username" placeholder="用户名" class="w-40" />
        <a-input v-model:value="filters.account" placeholder="账号" class="w-40" />
        <a-select v-model:value="filters.types" mode="multiple" placeholder="所属组别" :options="typeOptions" class="w-40" />
        <a-select v-model:value="filters.products" mode="multiple" placeholder="产品" :options="productOptions"
          class="w-40" />
        <a-select v-model:value="filters.permissions" mode="multiple" placeholder="权限" :options="permissionOptions"
          class="w-40" />
        <a-button type="primary" @click="handleSearch" class="flex items-center">
          <template #icon>
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </template>
          查询
        </a-button>
        <a-button @click="handleReset" class="flex items-center">
          <template #icon>
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
          </template>
          重置
        </a-button>
        <a-button type="primary" class="flex items-center" @click="showAddDialog">
          <template #icon>
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
            </svg>
          </template>
          添加用户
        </a-button>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <a-table :columns="columns" :data-source="filteredData" :pagination="pagination" @change="handleTableChange"
      class="bg-white rounded-lg shadow-sm">
      <!-- 状态列自定义渲染 -->
      <template #bodyCell="{ column, record }">
        <!-- 产品组列 -->
        <template v-if="column.key === 'products'">
          <div class="flex flex-wrap gap-1 max-w-[300px]">
            <template v-if="record.products && typeof record.products === 'string'">
              <a-tooltip v-for="(product, index) in record.products.split(',')" :key="index" :title="product?.trim() || ''" placement="top">
                <a-tag class="min-w-[80px] max-w-[150px] truncate">
                  {{ product?.trim() || '' }}
                </a-tag>
              </a-tooltip>
            </template>
            <template v-else>
              <a-tag>无</a-tag>
            </template>
          </div>
        </template>
        <!-- 操作列 -->
        <template v-if="column.key === 'action'">
          <div class="space-x-4">
            <a-tooltip title="修改用户信息">
              <a-button type="link" size="small" @click="handleEdit(record)">
                <template #icon>
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                </template>
              </a-button>
            </a-tooltip>
            <a-tooltip title="重置密码">
              <a-button type="link" size="small" @click="handleResetPassword(record)">
                <template #icon>
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
                  </svg>
                </template>
              </a-button>
            </a-tooltip>
            <a-tooltip title="设置为管理员">
              <a-button type="link" size="small" @click="handleSetAdmin(record)" :disabled="record.role === '管理员' || record.role === '超级管理员'">
                <template #icon>
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                  </svg>
                </template>
              </a-button>
            </a-tooltip>
            <a-tooltip title="删除用户">
              <a-button type="link" size="small" danger @click="handleDelete(record)">
                <template #icon>
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </template>
              </a-button>
            </a-tooltip>
          </div>
        </template>
      </template>
    </a-table>
    <AddUserDialog
      v-model:visible="addDialogVisible"
      :typeOptions="typeOptions"
      :productOptions="productOptions"
      @success="handleAddSuccess"
    />
    <EditUserDialog
      v-model:visible="editDialogVisible"
      :typeOptions="typeOptions"
      :productOptions="productOptions"
      :userData="currentUser"
      @success="handleAddSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import AddUserDialog from './AddUserDialog.vue';
import EditUserDialog from './EditUserDialog.vue';
import { useRouter } from 'vue-router';
import { getUserList,getProjectList,resetPassword,deleteUser } from '@/utils/api';
import { message } from 'ant-design-vue';
import { getRoleName,getTypeName,getProductName,typeMapping, roleMapping } from '@/utils/constantsMapping';
import $loading from '@/utils/loading';
import { Modal } from 'ant-design-vue';
const router = useRouter();
import { updateUser } from '@/utils/api';

// 搜索文本
const searchText = ref('');

// 表格列定义
const columns = [
  {
    title: '序号',
    key: 'index',
    width: '80px',
    customRender: ({ index }) => index + 1
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '账号',
    dataIndex: 'account',
    key: 'account',
  },
  {
    title: '所属组别',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '产品组',
    dataIndex: 'products',
    key: 'products',
    width: '300px',
    ellipsis: true
  },
  {
    title: '权限',
    dataIndex: 'role',
    key: 'role',
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
  },
];

// 真实数据
const data = ref<{
  key: string;
  id: string;
  username: string;
  account: string;
  type: string;
  products: string[];
  role: string;
  status: string;
}[]>([]);

// 分页配置
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
});

// 获取用户列表
const fetchUserList = async () => {
  const loadingInstance = $loading.show();
  try {
    const res = await getUserList({
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize
    });
    console.log("用户数据",res);
    data.value = res.records.map((item, index) => ({
      key: String(index),
      id: item.userId,
      managementId: item.managementId,
      username: item.realName || '',
      account: item.accountName || '',
      type: getTypeName(item.userType) || '无',
      products: item.product ? String(item.product).split(',').map(id => getProductName(id.trim())).join(', ') : '无',
      role: getRoleName(item.role) || '无'
    }));
    pagination.value.total = res.total || 0;
    filterData();
  } catch (error) {
    message.error('请求失败');
  } finally {
    loadingInstance.close();
  }
};

onMounted(() => {
  fetchUserList();
});

// 筛选条件
const filters = ref({
  username: '',
  account: '',
  types: [],
  products: [],
  permissions: []
});

const getTypeOptions = () => {
  return Object.entries(typeMapping).map(([value, label]) => ({ value, label }));
};

const getPermissionOptions = () => {
  return Object.entries(roleMapping).map(([value, label]) => ({ value, label }));
};

const typeOptions = getTypeOptions();
const productOptions = ref<{value: string, label: string}[]>([]);

onMounted(async () => {
  try {
    const res = await getProjectList();
    console.log("产品组数据",res);
    productOptions.value = res.map((item: any) => ({
      value: item.id.toString(),
      label: item.name
    }));
  } catch (error) {
    console.error('获取产品组列表失败:', error);
  }
});
const permissionOptions = getPermissionOptions();

// 筛选数据函数
const filteredData = ref([]);

const filterData = () => {
  if (!data.value || data.value.length === 0) return;
  
  filteredData.value = data.value.filter(item => {
    const matchUsername = !filters.value.username || item.username?.toLowerCase().includes(filters.value.username.toLowerCase());
    const matchAccount = !filters.value.account || item.account?.toLowerCase().includes(filters.value.account.toLowerCase());
    const matchTypes = filters.value.types.length === 0 || filters.value.types.some(t => {
      const mappedType = typeMapping[t as keyof typeof typeMapping];
      return mappedType ? item.type?.includes(mappedType) : item.type?.includes(t);
    });
    const matchProducts = filters.value.products.length === 0 || (item.products && typeof item.products === 'string' ? item.products.split(',').some(p => {
      const productId = productOptions.value.find(opt => opt.label === p.trim())?.value;
      return productId ? filters.value.products.includes(productId) : false;
    }) : false);
    const matchPermissions = filters.value.permissions.length === 0 || item.role && filters.value.permissions.some(p => {
      const mappedPermission = roleMapping[p as keyof typeof roleMapping];
      return mappedPermission ? item.role === mappedPermission : item.role === p;
    });

    return matchUsername && matchAccount && matchTypes && matchProducts && matchPermissions;
  });
};

// 搜索处理函数
const handleSearch = () => {
  pagination.value.current = 1;
  fetchUserList().then(() => {
    filterData();
  });
};

// 初始化时调用一次
onMounted(async () => {
  await fetchUserList();
  filterData();
});

// 重置处理函数
const handleReset = () => {
  filters.value = {
    username: '',
    account: '',
    types: [],
    products: [],
    permissions: []
  };
  pagination.value.current = 1;
  fetchUserList();
};

// 表格变化处理函数
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  fetchUserList();
};

// 编辑用户对话框
const editDialogVisible = ref(false);
const currentUser = ref<any>(null);

// 编辑用户处理函数
const handleEdit = (record: any) => {
  console.log('编辑用户:', record);
  currentUser.value = {
    id: record.managementId,
    username: record.username,
    type: Object.keys(typeMapping).find(key => typeMapping[key as keyof typeof typeMapping] === record.type) || '',
    products: record.products ? record.products.split(', ').map(name => {
      const option = productOptions.value.find(opt => opt.label === name.trim());
      return option ? option.value : '';
    }).filter(Boolean).join(',') : ''
  };
  editDialogVisible.value = true;
};

// 重置密码处理函数
const handleResetPassword = (record: any) => {
  Modal.confirm({
    title: '确认重置密码',
    content: `确定要重置用户 ${record.username} 的密码吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      const loadingInstance = $loading.show();
      try {
        await resetPassword(record.id);
        message.success('密码重置成功');
      } catch (error) {
        message.error('密码重置失败');
      } finally {
        loadingInstance.close();
      }
    }
  });
};

// 设置管理员处理函数
const handleSetAdmin = async (record: any) => {
  Modal.confirm({
    title: '确认设置',
    content: `确定要将用户 ${record.username} 设置为管理员吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      const loadingInstance = $loading.show();
      try {
        console
        await updateUser({
          managementId: record.managementId,
          role: 'admin'
        });
        message.success('设置管理员成功');
        fetchUserList();
      } catch (error) {
        message.error('设置管理员失败');
      } finally {
        loadingInstance.close();
      }
    }
  });
};

// 删除用户处理函数
const handleDelete = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 ${record.username} 吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      const loadingInstance = $loading.show();
      try {
        await deleteUser({
          managementId: record.managementId,
          userId: record.id
        });
        message.success('删除用户成功');
        fetchUserList();
      } catch (error) {
        message.error('删除用户失败');
      } finally {
        loadingInstance.close();
      }
    }
  });
};

// 添加用户对话框
const addDialogVisible = ref(false);
const showAddDialog = () => {
  addDialogVisible.value = true;
};

const handleAddSuccess = () => {
  fetchUserList();
};
</script>

<style scoped>
:deep(.ant-input) {
  text-align: left;
}

:deep(.ant-select-selection-placeholder),
:deep(.ant-select-selection-item) {
  text-align: left;
}
</style>